const multer = require('multer');
const path = require('path');
const { success, error } = require('../utils/response');
const picxService = require('../services/picxService');

// 配置 multer 存储
const storage = multer.memoryStorage();

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 允许的文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('Invalid file type. Only JPEG, PNG, GIF and WebP are allowed.'), false);
  }
};

// 创建 multer 实例
const upload = multer({
  storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  },
  fileFilter
});

/**
 * 上传图片
 * @route POST /api/upload/image
 */
const uploadImage = async (req, res) => {
  try {
    // 检查是否有文件
    if (!req.file) {
      return error(res, 'No file uploaded', 400);
    }
    
    // 获取文件信息
    const { buffer, originalname } = req.file;
    
    // 上传到 PicX
    const imageUrl = await picxService.uploadImage(buffer, originalname);
    
    return success(res, { url: imageUrl }, 'Image uploaded successfully', 201);
  } catch (err) {
    console.error('Upload image error:', err);
    return error(res, err.message || 'Failed to upload image', 500);
  }
};

// 导出中间件处理函数
const handleImageUpload = (req, res, next) => {
  // 使用 multer 处理单个文件上传
  upload.single('image')(req, res, (err) => {
    if (err) {
      if (err instanceof multer.MulterError) {
        // Multer 错误
        if (err.code === 'LIMIT_FILE_SIZE') {
          return error(res, 'File too large. Maximum size is 5MB.', 400);
        }
        return error(res, err.message, 400);
      }
      
      // 其他错误
      return error(res, err.message, 400);
    }
    
    next();
  });
};

module.exports = {
  uploadImage,
  handleImageUpload
};
